from PySide6.QtWidgets import QWidget,QMessageBox,QTableWidgetItem,QHeaderView,QMenu,QAbstractItemView
from PySide6.QtCore import Qt
from sqlalchemy.orm import Session
import pandas as pd

from views.person.persontype.persontype import Ui_persontype
from settings.publicFuncation.exceldownloadimport import OperationModel
from settings.publicvar import engine
from views.person.model.person import PersonType
from views.person.persontype.operationpersontypeView import OperationPersonTypeView

class PersonTypeView(QWidget,Ui_persontype):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.persontypetable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.persontypetable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.persontypetable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.persontypetable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.persontypetable.customContextMenuRequested.connect(self.generate_menu)
        self.addbtn.clicked.connect(self.addFun)
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.importbtn.clicked.connect(self.importdataFun)
        self.sereachedit.editingFinished.connect(self.sereachFun)
        self.serearchbtn.clicked.connect(self.sereachFun)
        self.autoLoadData()
        self.loadTableData()

    # 表结构设置
    def SetTableStructure(self, data):
        self.persontypetable.setRowCount(len(data))
        for i, persontype in enumerate(data):
            ind = QTableWidgetItem(str(persontype.id))
            self.persontypetable.setItem(i, 0, ind)
            persontype_name = QTableWidgetItem(persontype.persontype)
            self.persontypetable.setItem(i, 1, persontype_name)
            mark = QTableWidgetItem(persontype.mark)
            self.persontypetable.setItem(i, 2, mark)
    # 加载数据
    def loadTableData(self):
        with Session(engine) as session,session.begin():
            data =  session.query(PersonType).all()
            self.SetTableStructure(data)

    def autoLoadData(self):
        names = ['idx', 'persontype', 'mark']
        url = 'state/model/人员类型模板.xlsx'
        try:
            data = pd.read_excel(url, sheet_name=0, header=1,
                                 names=names,
                                 dtype={'persontype':str,'mark':str}
                                 ).drop('idx', axis=1)
            with Session(engine) as session, session.begin():
                exist_persontype = session.query(PersonType).filter(
                    PersonType.persontype.in_(data.persontype.to_list()))
                persontypes = [persontype.persontype for persontype in exist_persontype]
                save_data = data[~data.persontype.isin(persontypes)].to_dict('records')
                save_persontypes = [PersonType(**item) for item in save_data]
                session.add_all(save_persontypes)
        except:
            QMessageBox.information(None,'失败','数据加载失败')

    def generate_menu(self, pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deletitem = menu.addAction('删除')
        action = menu.exec(self.persontypetable.mapToGlobal(pos))
        posrow = self.persontypetable.currentRow()
        columns = self.persontypetable.columnCount()
        data = [self.persontypetable.item(posrow, i).text() for i in range(columns)]
        if action == changeitem:
            changeother = OperationPersonTypeView('change',data)
            changeother.exec()
        elif action == deletitem:
            deleteother = OperationPersonTypeView('delete',data)
            deleteother.exec()
        elif action == viewitem:
            viewother = OperationPersonTypeView('view',data)
            viewother.exec()
        self.loadTableData()

    # 搜索
    def sereachFun(self):
        sereachedit = self.sereachedit.text().strip()
        if sereachedit == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.loadTableData()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonType).filter(
                    PersonType.persontype.like('%' + sereachedit + '%')).all()
                if sereachedit:
                    self.SetTableStructure(sereachName)

    def addFun(self):
        persontype = OperationPersonTypeView('add',False)
        persontype.exec()
        self.loadTableData()

    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('人员类型模板.xlsx')

    def importdataFun(self):
        names = ['idx', 'persontype','mark']
        data = OperationModel().importdataFun(names)
        with Session(engine) as session,session.begin():
            exist_persontype = session.query(PersonType).filter(PersonType.persontype.in_(data.persontype.to_list()))
            persontypes = [persontype.persontype for persontype in exist_persontype]
            save_data = data[~data.persontype.isin(persontypes)].to_dict('records')
            save_persontypes = [PersonType(**item) for item in save_data]
            session.add_all(save_persontypes)
            QMessageBox.information(None, '导入信息', '你导入成功%s条，失败%s条！' % (
            len(save_persontypes), (len(data) - len(save_persontypes))))
        self.loadTableData()

